/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.sx.sx1.lintcode.day717.filetransfor;

import com.jcraft.jsch.*;
import java.util.*;
import java.io.*;

//Java SFTP下载整个目录
//https://blog.51cto.com/u_16213383/8824941
public class SFTPUtils {

    public static void main(String[] args) {
        //使用
        String hostname = "192.168.100.107";
        int port = 22;
        String username = "king";
        String password = "123456";
        String remotePath = "/home/king/code";
        String localPath = "F:\\netbeanxm\\sftp";

        SFTPUtils sftpUtils = new SFTPUtils(hostname, port, username, password);
        try {
            sftpUtils.downloadDirectory(remotePath, localPath);
            System.out.println("Download completed successfully.");
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }

    private String hostname;
    private int port;
    private String username;
    private String password;

    public SFTPUtils(String hostname, int port, String username, String password) {
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public void downloadDirectory(String remotePath, String localPath) throws JSchException, SftpException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();

        downloadDirectory(channel, remotePath, localPath);

        channel.disconnect();
        session.disconnect();
    }

    private void downloadDirectory(ChannelSftp channel, String remotePath, String localPath) throws SftpException {
        channel.cd(remotePath);
        Vector<ChannelSftp.LsEntry> entries = channel.ls("*");

        for (ChannelSftp.LsEntry entry : entries) {
            if (entry.getAttrs().isDir()) {
                if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {
                    String newRemotePath = remotePath + "/" + entry.getFilename();
                    String newLocalPath = localPath + "/" + entry.getFilename();
                    new File(newLocalPath).mkdirs();
                    downloadDirectory(channel, newRemotePath, newLocalPath);
                }
            } else {
                channel.get(remotePath + "/" + entry.getFilename(), localPath + "/" + entry.getFilename());
            }
        }
    }
}
